package todo;


import se.lth.cs.realtime.*;
import se.lth.cs.realtime.event.AckEvent;
import done.AbstractWashingMachine;


public class WaterController extends PeriodicThread {
	AbstractWashingMachine washingMachine;
	int currentMode;
	double currentWaterLevel;
	RTThread source;
	double speed;
	boolean isAcked;
	// TODO: add suitable attributes

	public WaterController(AbstractWashingMachine mach, double speed) {
		super((long) (1000/speed)); // TODO: replace with suitable period
		washingMachine = mach;
		currentMode = WaterEvent.WATER_IDLE;
		this.speed = speed;
	}

	public void perform() {
		
		WaterEvent waterEvent = (WaterEvent) mailbox.tryFetch();
		
		if (waterEvent != null){
			source = (RTThread) waterEvent.getSource();
			currentMode = waterEvent.getMode();
			currentWaterLevel = waterEvent.getLevel();
			isAcked = false;
		}
		
		switch (currentMode){
		case WaterEvent.WATER_DRAIN:
			washingMachine.setDrain(true);
			washingMachine.setFill(false);
			if (currentWaterLevel >= washingMachine.getWaterLevel() && !isAcked){
				isAcked = true;
				source.putEvent(new AckEvent());
			}
			
			
			break;
		case WaterEvent.WATER_FILL:
			if (washingMachine.getSpinValue() == SpinEvent.SPIN_FAST){
				System.out.println("You are not allowed to fill water when centrifuging");
			} else {
				washingMachine.setDrain(false);
				washingMachine.setFill(true);
				if (currentWaterLevel <= washingMachine.getWaterLevel() && !isAcked){
					isAcked = true;
					source.putEvent(new AckEvent());
				}
			}
			
			
			break;
			
		case WaterEvent.WATER_IDLE:
			washingMachine.setDrain(false);
			washingMachine.setFill(false);
			break;
		}
	}
}
